/**
 * FormNotaDespesa.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormNotaDespesa.java
 *
 * Created on 22/06/2009, 19:25:56
 */

package frames;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import negocio.notas.*;
import negocio.pessoas.Empreendimento;
import negocio.pessoas.Pessoa;
import utils.*;

/**
 *
 * @author jmsandy
 */
public class FormNotaDespesa extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private NotaDespesa nota   = null;
    private Empreendimento emp = null;
    private Pessoa fornecedor  = null;
    private ArrayList lstDesp  = null;
    private ArrayList lstObj   = null;
    private int posicao        = 0;
    private int statusEmp      = K_FIELDS_NOVO;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormNotaDespesa */
    public FormNotaDespesa() {
        initComponents();
        initializeMyComponents();
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constants">
    private static final int K_FIELDS_BUSCA = 1;
    private static final int K_FIELDS_NOVO  = 2;
    public static final int K_FORM_CADASTRO = 4;
    public static final int K_FORM_PESQUISA = 5;
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormNotaDespesa().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panel = new javax.swing.JPanel();
        lbDespesa = new javax.swing.JLabel();
        cbDespesa = new javax.swing.JComboBox();
        lbNumNota = new javax.swing.JLabel();
        textNumNota = new javax.swing.JTextField();
        lbSerie = new javax.swing.JLabel();
        textSerie = new javax.swing.JTextField();
        lbDataEntrada = new javax.swing.JLabel();
        lbDataEmissao = new javax.swing.JLabel();
        lbFornecedor = new javax.swing.JLabel();
        textFornecedor = new javax.swing.JTextField();
        lbValorTotal = new javax.swing.JLabel();
        textValorTotal = new javax.swing.JTextField();
        lbEmpreendimento = new javax.swing.JLabel();
        textDtEntrada = new javax.swing.JFormattedTextField();
        textDtEmissao = new javax.swing.JFormattedTextField();
        btnFornecedor = new javax.swing.JButton();
        textEmpreendimento = new javax.swing.JTextField();
        btnEmp = new javax.swing.JButton();
        panelBotao = new javax.swing.JPanel();
        btnBuscar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jPanelNavegacao = new javax.swing.JPanel();
        btnFirst = new javax.swing.JButton();
        btnPrevious = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();

        setTitle("Nota de Despesa");
        setName("formNotaDespesa"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        panel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lbDespesa.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDespesa.setText("*Despesa");

        cbDespesa.setBackground(java.awt.Color.white);
        cbDespesa.setFont(new java.awt.Font("SansSerif", 0, 12));
        cbDespesa.setEnabled(false);

        lbNumNota.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbNumNota.setText("*Nº Nota");

        textNumNota.setBackground(java.awt.Color.white);
        textNumNota.setEditable(false);
        textNumNota.setFont(new java.awt.Font("SansSerif", 0, 12));
        textNumNota.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textNumNota.setPreferredSize(new java.awt.Dimension(10, 26));

        lbSerie.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbSerie.setText("Série");

        textSerie.setBackground(java.awt.Color.white);
        textSerie.setEditable(false);
        textSerie.setFont(new java.awt.Font("SansSerif", 0, 12));
        textSerie.setPreferredSize(new java.awt.Dimension(10, 26));

        lbDataEntrada.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDataEntrada.setText("*Data de Entrada");

        lbDataEmissao.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDataEmissao.setText("*Data de Emissão");

        lbFornecedor.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbFornecedor.setText("*Fornecedor");

        textFornecedor.setBackground(java.awt.Color.white);
        textFornecedor.setEditable(false);
        textFornecedor.setFont(new java.awt.Font("SansSerif", 0, 12));
        textFornecedor.setPreferredSize(new java.awt.Dimension(10, 26));

        lbValorTotal.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbValorTotal.setText("*Valor Total");

        textValorTotal.setBackground(java.awt.Color.white);
        textValorTotal.setEditable(false);
        textValorTotal.setFont(new java.awt.Font("SansSerif", 0, 12));
        textValorTotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValorTotal.setPreferredSize(new java.awt.Dimension(10, 26));
        textValorTotal.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textValorTotalFocusLost(evt);
            }
        });

        lbEmpreendimento.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbEmpreendimento.setText("*Empreendimento");

        textDtEntrada.setBackground(java.awt.Color.white);
        textDtEntrada.setEditable(false);
        try {
            textDtEntrada.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textDtEntrada.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textDtEntrada.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textDtEntrada.setFont(new java.awt.Font("SansSerif", 0, 12));

        textDtEmissao.setBackground(java.awt.Color.white);
        textDtEmissao.setEditable(false);
        try {
            textDtEmissao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textDtEmissao.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textDtEmissao.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textDtEmissao.setFont(new java.awt.Font("SansSerif", 0, 12));

        btnFornecedor.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnFornecedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.png"))); // NOI18N
        btnFornecedor.setBorderPainted(false);
        btnFornecedor.setContentAreaFilled(false);
        btnFornecedor.setEnabled(false);
        btnFornecedor.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnFornecedorMouseClicked(evt);
            }
        });

        textEmpreendimento.setBackground(java.awt.Color.white);
        textEmpreendimento.setEditable(false);
        textEmpreendimento.setFont(new java.awt.Font("SansSerif", 0, 12));
        textEmpreendimento.setPreferredSize(new java.awt.Dimension(10, 26));

        btnEmp.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnEmp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.png"))); // NOI18N
        btnEmp.setBorderPainted(false);
        btnEmp.setContentAreaFilled(false);
        btnEmp.setEnabled(false);
        btnEmp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEmpMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbValorTotal)
                        .addGap(48, 48, 48)
                        .addComponent(textValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelLayout.createSequentialGroup()
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lbEmpreendimento))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lbNumNota))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lbFornecedor))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lbDataEntrada))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(lbDespesa)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelLayout.createSequentialGroup()
                                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(textNumNota, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)
                                    .addComponent(textDtEntrada, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                                .addComponent(lbDataEmissao)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(textDtEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(panelLayout.createSequentialGroup()
                                        .addComponent(lbSerie)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(textSerie, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addComponent(textFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 25, Short.MAX_VALUE))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addComponent(textEmpreendimento, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEmp, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cbDespesa, 0, 392, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelLayout.createSequentialGroup()
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lbDespesa)
                            .addComponent(cbDespesa, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(7, 7, 7)
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(btnEmp, 0, 0, Short.MAX_VALUE)
                            .addComponent(lbEmpreendimento)
                            .addComponent(textEmpreendimento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(panelLayout.createSequentialGroup()
                                .addComponent(textNumNota, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(3, 3, 3)
                                .addComponent(textDtEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(panelLayout.createSequentialGroup()
                                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                                    .addComponent(textSerie, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lbSerie))
                                .addGap(3, 3, 3)
                                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(textDtEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lbDataEmissao))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE)
                            .addComponent(textFornecedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lbFornecedor))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lbValorTotal)
                            .addComponent(textValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLayout.createSequentialGroup()
                        .addComponent(lbNumNota)
                        .addGap(108, 108, 108))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLayout.createSequentialGroup()
                        .addComponent(lbDataEntrada)
                        .addGap(76, 76, 76))))
        );

        panelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textEmpreendimento, textFornecedor});

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnBuscar.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/find.png"))); // NOI18N
        btnBuscar.setText("Procurar");
        btnBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnBuscarMouseClicked(evt);
            }
        });

        btnNovo.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/new.png"))); // NOI18N
        btnNovo.setText("Novo     ");
        btnNovo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNovoMouseClicked(evt);
            }
        });

        btnCancel.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancel.setText("Cancelar");
        btnCancel.setMaximumSize(new java.awt.Dimension(92, 34));
        btnCancel.setMinimumSize(new java.awt.Dimension(92, 34));
        btnCancel.setPreferredSize(new java.awt.Dimension(92, 34));
        btnCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelMouseClicked(evt);
            }
        });

        btnExcluir.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/delete.png"))); // NOI18N
        btnExcluir.setText("Excluir   ");
        btnExcluir.setMaximumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setMinimumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setPreferredSize(new java.awt.Dimension(92, 34));
        btnExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnExcluirMouseClicked(evt);
            }
        });

        jPanelNavegacao.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnFirst.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnFirst.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/first.png"))); // NOI18N
        btnFirst.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnFirst.setContentAreaFilled(false);
        btnFirst.setEnabled(false);
        btnFirst.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnFirstMouseClicked(evt);
            }
        });

        btnPrevious.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnPrevious.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/previous.png"))); // NOI18N
        btnPrevious.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnPrevious.setContentAreaFilled(false);
        btnPrevious.setEnabled(false);
        btnPrevious.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnPreviousMouseClicked(evt);
            }
        });

        btnNext.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/next.png"))); // NOI18N
        btnNext.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnNext.setContentAreaFilled(false);
        btnNext.setEnabled(false);
        btnNext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNextMouseClicked(evt);
            }
        });

        btnLast.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnLast.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/last.png"))); // NOI18N
        btnLast.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnLast.setContentAreaFilled(false);
        btnLast.setEnabled(false);
        btnLast.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnLastMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanelNavegacaoLayout = new javax.swing.GroupLayout(jPanelNavegacao);
        jPanelNavegacao.setLayout(jPanelNavegacaoLayout);
        jPanelNavegacaoLayout.setHorizontalGroup(
            jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelNavegacaoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnFirst)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPrevious)
                .addGap(10, 10, 10)
                .addComponent(btnNext)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLast)
                .addContainerGap())
        );
        jPanelNavegacaoLayout.setVerticalGroup(
            jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(btnFirst)
            .addComponent(btnPrevious)
            .addComponent(btnNext)
            .addComponent(btnLast)
        );

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelBotaoLayout.createSequentialGroup()
                        .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelBotaoLayout.createSequentialGroup()
                        .addGap(157, 157, 157)
                        .addComponent(jPanelNavegacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(52, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnBuscar, btnCancel, btnExcluir, btnNovo});

        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnBuscar, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnNovo, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnCancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanelNavegacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBuscar, btnCancel, btnExcluir, btnNovo});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(panelBotao, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-567)/2, (screenSize.height-376)/2, 567, 376);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Busca de Fornecedores">   
    // Realiza a busca do fornecedor
    private void btnFornecedorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFornecedorMouseClicked
        if(btnFornecedor.isEnabled()){

            FormFornecedor form = new FormFornecedor(FormFornecedor.K_FORM_PESQUISA);
            form.setModal(true);
            form.setVisible(true);

            this.fornecedor = new Pessoa();
            this.fornecedor = form.getFornecedor();
            form.dispose();
            this.textFornecedor.setText(this.fornecedor != null ?
                this.fornecedor.getNome() : "");
        }
    }//GEN-LAST:event_btnFornecedorMouseClicked
    //</editor-fold>
    
    private void textValorTotalFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textValorTotalFocusLost
        try{
            if(textValorTotal.isEnabled() &&
                                textValorTotal.getText().trim().length() > 0){
                DecimalFormat format = new DecimalFormat("0.00");

                textValorTotal.setText(format.format(
                Double.parseDouble(textValorTotal.getText())).replace(',', '.'));
            }
        }
        catch(Exception ex){
            showMessageWarning(ErrorMessage.MSG_GERAL_FORMAT);
        }
    }//GEN-LAST:event_textValorTotalFocusLost

    // Fecha o formulario
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    //<editor-fold defaultstate="collapsed" desc="Eventos CRUD ">
    /**
     * Responsavel por criar um novo objeto unidade ou salva-lo. Dependendo
     * do estado do atual do botao.
     */
    private void btnNovoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoMouseClicked
        try{
            if(btnNovo.isEnabled()){
                // Verifica o estado do botao
                if(this.btnNovo.getText().startsWith("Novo")){
                    clearFields(); // Limpa o formulario
                    StateMachineButton.changeState(getLstButton(1),
                                                       StateMachineButton.NOVO);
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);

                    // Cria uma nova nota e seta os campos para edicao
                    this.nota = new NotaDespesa();
                    enableFields(true);
                    this.textValorTotal.setText("0.00");
                    this.statusEmp = K_FIELDS_NOVO;
                }
                else{
                    // Verifica se todos os campos foram mapeados com sucesso
                    if(mapFields(K_FIELDS_NOVO)){
                        boolean flag = false;

                        // Verifica se a existem as notas cadastradas
                        boolean exists = (new Nota()).exists(nota.getNumNota(),
                                            nota.getSerie(),
                                            fornecedor.getCod_objeto(),
                                            nota.getCod_objeto());
                        if(!exists){
                            // Verifica se e uma nova nota ou se
                            // apenas para atualizar
                            if(this.nota.isNew()){
                                flag = this.nota.insert();

                                if(flag){
                                    this.lstObj = null;
                                    StateMachineButton.changeState(
                                    getLstButton(1), StateMachineButton.SALVAR);
                                }
                            }
                            else{
                                flag = this.nota.update();

                                if(flag){
                                    mudarEstadoNavegacao();
                                    StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                                }
                            }
                        }
                        else{
                            showMessageError(ErrorMessage.MSG_NOTA_EXISTENTE);
                        }
                        // Verifica se foi inserido com sucesso no banco de dados
                        if(flag){
                            this.nota.setIsNew(false);
                            enableFields(false);

                            // Exibe formulario de itens
                            showFormContas(FormContas.K_FORM_CADASTRO);
                        }
                        else{
                            if(!exists)
                                showMessageError(nota.getErrorMessage());
                        }
                    }
                    else{
                        showMessageError(ErrorMessage.MSG_GERAL_OBRIG);
                    }
                }
            }
        }
        catch(IOException ex){ }
    }//GEN-LAST:event_btnNovoMouseClicked

    /**
     * Busca e recupera uma lista de notas com os filtros informados
     */
    private void btnBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnBuscarMouseClicked
        try{
            if(btnBuscar.isEnabled()){
                // Verifica o estado do botao
                if(this.btnBuscar.getText().startsWith("Procurar")){
                    clearFields(); // Limpa o formulario

                    StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.PROCURAR);

                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                    // Seta os campos como editaveis
                    enableFields(true);
                    this.nota = new NotaDespesa();
                    this.fornecedor = null;
                    this.emp = null;
                    this.statusEmp = K_FIELDS_BUSCA;
                }
                else{
                    // cria uma nova lista de orcamentos
                    this.lstObj = new ArrayList();
                    mapFields(K_FIELDS_BUSCA);

                    lstObj = this.nota.recLstNotasDespesas(this.nota);

                    // Verifica se ocorreu algum erro na busca de despesa
                    if(this.nota.getErrorMessage().equals("")){
                        // Verifica se foi recuperado algum objeto
                        if(lstObj != null && lstObj.size() > 0){
                            enableFields(false);

                            StateMachineNavigator.changeState(getLstButton(2),
                             lstObj.size() == 1 ?
                                 StateMachineNavigator.PADRAO :
                                 StateMachineNavigator.PRIMEIRO);

                            StateMachineButton.changeState(getLstButton(1),
                                    StateMachineButton.RECUPERAR);

                            // Apresenta a primeira nota
                            mostraNota((NotaDespesa)lstObj.get(0));
                        }
                        else{
                            showMessageWarning(ErrorMessage.MSG_NOTA_BUSCA);
                        }
                    }
                    else{
                        showMessageError(nota.getErrorMessage());
                    }
                }
            }
        }
        catch(IOException ex){}
    }//GEN-LAST:event_btnBuscarMouseClicked

    /**
     * Cancela uma acao corrente de insercao ou edicao. Responsavel tambem por
     * abrir um registro para edicao.
     */
    private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked
        try{
            if(btnCancel.isEnabled()){
                // Verifica o estado do botao
                if(this.btnCancel.getText().startsWith("Cancelar")){

                    // Realiza a confirmacao da acao pelo usuario
                    if(JOptionPane.showConfirmDialog(this, "Confirma o cancelam"
                         +"ento?", "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                        enableFields(false); // Desabilita os campos

                        if(this.nota.isNew()){
                            clearFields();
                            StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.INICIAL);
                        }
                        else{
                            StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                            mudarEstadoNavegacao();
                        }
                    }
                }
                else{
                    /**
                     * Somente as notas que nao foram transformados confirmadas
                     * podem ser editadas.
                     */
                    if(nota.getSituacao() != StatusNota.CONFIRMADO){
                        enableFields(true);
                        this.nota.setWasUpdated(true);
                        StateMachineButton.changeState(getLstButton(1),
                                                     StateMachineButton.EDITAR);
                        StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                    }
                    else{
                        // Exibe formulario de itens
                        showFormContas(FormContas.K_FORM_EXIBICAO);
                    }
                }
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnCancelMouseClicked

    /**
     * Exclui uma nota da base de dados
     */
    private void btnExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExcluirMouseClicked
        try{
            if(btnExcluir.isEnabled()){
                // Realiza a confirmacao da acao pelo usuario
                if(JOptionPane.showConfirmDialog(this, "Confirma a exclusão?",
                       "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                    boolean flag = this.nota.delete();
                    if(flag){
                        clearFields();

                        enableFields(false); // Desabilita os campos

                        // Verifica o tamanho da lista
                        if(lstObj != null){
                            // Remove o item da lista corrente
                            lstObj.remove(this.posicao);

                            // Posiciona na base de navegacao
                            mudarEstadoNavegacao();

                            if(lstObj.isEmpty()){
                                StateMachineButton.changeState(getLstButton(1),
                                                StateMachineButton.EXCLUIR);
                            }
                            else{
                                StateMachineButton.changeState(getLstButton(1),
                                               StateMachineButton.CANCELAR);
                            }
                        }
                        else{
                            StateMachineButton.changeState(getLstButton(1),
                                                StateMachineButton.EXCLUIR);
                        }
                    }
                    else{
                        showMessageError(nota.getErrorMessage());
                    }
                }
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnExcluirMouseClicked
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Barra Navegacao">
    /**
     * Move para a primeira posicao da lista de notas
     */
    private void btnFirstMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFirstMouseClicked
        try{
            // Verifica o tamanho da lista de notas
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnFirst.isEnabled()){

                // Posiciona na posicao inicial
                StateMachineNavigator.changeState(getLstButton(2),
                        StateMachineNavigator.PRIMEIRO);
                this.posicao = 0;
                mostraNota((NotaDespesa)lstObj.get(this.posicao));
            }
        } catch(Exception ex){ }
}//GEN-LAST:event_btnFirstMouseClicked

    /**
     * Move para a ultima posicao da lista de notas
     */
    private void btnPreviousMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnPreviousMouseClicked
        try{
            // Verifica o tamanho da lista de notas
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnPrevious.isEnabled()){

                this.posicao--; // Recebe a proxima posicao

                if(this.posicao >= 1){
                    StateMachineNavigator.changeState(getLstButton(2),
                            StateMachineNavigator.ANTERIOR_MAIOR);
                } else{
                    StateMachineNavigator.changeState(getLstButton(2),
                            StateMachineNavigator.ANTERIOR_MENOR);
                }

                mostraNota((NotaDespesa)lstObj.get(this.posicao));
            }
        } catch(Exception ex){ }
}//GEN-LAST:event_btnPreviousMouseClicked

    /**
     * Posiciona na posicao anterior da lista
     */
    private void btnNextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNextMouseClicked
        try{
            // Verifica o tamanho da lista de notas
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnNext.isEnabled()){

                this.posicao++; // Recebe a proxima posicao

                if(this.posicao >= (lstObj.size() - 1)){
                    StateMachineNavigator.changeState(getLstButton(2),
                            StateMachineNavigator.PROXIMO_MENOR);
                } else{
                    StateMachineNavigator.changeState(getLstButton(2),
                            StateMachineNavigator.PROXIMO_MAIOR);
                }

                mostraNota((NotaDespesa)lstObj.get(this.posicao));
            }
        } catch(Exception ex){ }
}//GEN-LAST:event_btnNextMouseClicked

    /**
     * Move para a proxima unidade da lista de notas
     */
    private void btnLastMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLastMouseClicked
        try{
            // Verifica o tamanho da lista de notas
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnLast.isEnabled()){

                // Posiciona na posicao final
                StateMachineNavigator.changeState(getLstButton(2),
                        StateMachineNavigator.ULTIMO);
                this.posicao = lstObj.size() - 1;
                mostraNota((NotaDespesa)lstObj.get(this.posicao));
            }
        } catch(Exception ex){ }
}//GEN-LAST:event_btnLastMouseClicked
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Busca de Empreendimento">
    private void btnEmpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEmpMouseClicked
        if(btnEmp.isEnabled()){

            FormEmpreendimento form =
                    new FormEmpreendimento(FormEmpreendimento.K_FORM_PESQUISA);
            form.setModal(true);
            form.setVisible(true);

            this.emp = new Empreendimento();
            this.emp = form.getEmpreendimento();
            form.dispose();

            // Verifica o estado que o formulario se encontra e se o objeto
            // recuperado e valido
            if(this.statusEmp == K_FIELDS_BUSCA){
                this.textEmpreendimento.setText(this.emp != null ?
                        new Pessoa().recPessoaEmpreendimento(
                        this.emp.getCod_objeto()).getNome(): "");
            }
            else{
                if(this.emp.getStatus() == StatusEmpreendimento.ABERTO){
                    this.textEmpreendimento.setText(this.emp != null ?
                            new Pessoa().recPessoaEmpreendimento(
                            this.emp.getCod_objeto()).getNome(): "");
                }
                else{
                    showMessageError(ErrorMessage.MSG_NOTA_EMP);
                }
            }
        }
    }//GEN-LAST:event_btnEmpMouseClicked
    //</editor-fold>


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnEmp;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnFornecedor;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JComboBox cbDespesa;
    private javax.swing.JPanel jPanelNavegacao;
    private javax.swing.JLabel lbDataEmissao;
    private javax.swing.JLabel lbDataEntrada;
    private javax.swing.JLabel lbDespesa;
    private javax.swing.JLabel lbEmpreendimento;
    private javax.swing.JLabel lbFornecedor;
    private javax.swing.JLabel lbNumNota;
    private javax.swing.JLabel lbSerie;
    private javax.swing.JLabel lbValorTotal;
    private javax.swing.JPanel panel;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JFormattedTextField textDtEmissao;
    private javax.swing.JFormattedTextField textDtEntrada;
    private javax.swing.JTextField textEmpreendimento;
    private javax.swing.JTextField textFornecedor;
    private javax.swing.JTextField textNumNota;
    private javax.swing.JTextField textSerie;
    private javax.swing.JTextField textValorTotal;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Messagem de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Nota de Despesa",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageWarning(String msg){
        JOptionPane.showMessageDialog(this, msg, "Nota de Despesa",
                                                   JOptionPane.WARNING_MESSAGE);
    }

    private void showFormContas(int tipo){
        FormContas form = new FormContas(tipo, nota.getCod_objeto(),
                               nota.getEmpreendimento(), nota.getValorNota());
        form.setModal(true);
        form.setVisible(true);

        nota.setSituacao(
              form.getInserted() ? StatusNota.CONFIRMADO : StatusNota.PENDENTE);
        form.dispose();
    }

    // Recupera a lista de botoes do formulario
    private ArrayList<JButton> getLstButton(Integer situacao){
        ArrayList<JButton> lstButton = new ArrayList<JButton>();

        if(situacao == 1){
            lstButton.add(this.btnBuscar);
            lstButton.add(this.btnNovo);
            lstButton.add(this.btnCancel);
            lstButton.add(this.btnExcluir);
        }
        else{
            lstButton.add(this.btnFirst);
            lstButton.add(this.btnPrevious);
            lstButton.add(this.btnNext);
            lstButton.add(this.btnLast);
        }

        return lstButton;
    }

    // Monta lista de despesas
    private void populateComboDespesa(){
        // Recupera todos as despesas existentes
        lstDesp = new ArrayList();
        lstDesp = (new Despesa()).recLstDespesas("");

        // Popula o grid
        cbDespesa.removeAllItems();
        cbDespesa.addItem("");
        for(Despesa d :(ArrayList<Despesa>) lstDesp){
            cbDespesa.addItem(d.getDescricao());
        }
    }

    // Limpa os campos do formulario
    private void clearFields(){
        textDtEmissao.setText(null);
        textDtEntrada.setText(null);
        textFornecedor.setText("");
        textNumNota.setText("");
        textSerie.setText("");
        textValorTotal.setText("");
        textEmpreendimento.setText("");
        cbDespesa.setSelectedIndex(0);
    }

    // Controle dos campos para edicao
    private void enableFields(Boolean flag){
        textNumNota.setEditable(flag);
        textSerie.setEditable(flag);
        textDtEmissao.setEditable(flag);
        textDtEntrada.setEditable(flag);
        textValorTotal.setEditable(flag);
        btnFornecedor.setEnabled(flag);
        btnEmp.setEnabled(flag);
        cbDespesa.setEnabled(flag);
    }

    // Transfere os campos para o objeto para persistencia
    private boolean mapFields(int tipo){
        boolean map = true;

        try{
            // Formato padrao das dadas do sistema
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            sdf.setLenient(false);

            // Uppercase nos campos
            textFornecedor.setText(textFornecedor.getText().toUpperCase());

            // Mapeia os campos
            nota.setNumNota(textNumNota.getText().isEmpty() ?
                            null : Integer.parseInt(textNumNota.getText()));
            nota.setSerie(textSerie.getText());
            nota.setValorNota(textValorTotal.getText().isEmpty() ?
                     0 : Double.parseDouble(textValorTotal.getText()));
            nota.setDtEmissao(
                    (!textDtEmissao.getText().equals("  /  /    ")) ?
                     new Date(sdf.parse(textDtEmissao.getText()).getTime()) :
                                                                          null);
            nota.setDtEntrada(
                    (!textDtEntrada.getText().equals("  /  /    ")) ?
                     new Date(sdf.parse(textDtEntrada.getText()).getTime()) :
                                                                          null);
            map = mapAux(tipo);
        }
        catch(Exception ex){
            ex.printStackTrace();
            map = false;
        }
        return map;
    }

    // Mapeamenteo auxiliar dos campos
    private Boolean mapAux(int tipo){
        Boolean map = true;
        if(tipo != K_FIELDS_BUSCA){
            map = fornecedor != null ? true : false;
            if(map){
                nota.setFornecedor(fornecedor.getCod_objeto());

                map = cbDespesa.getSelectedIndex() > 0 ? true : false;
                if(map){
                    Despesa d =
                         (Despesa)lstDesp.get(cbDespesa.getSelectedIndex() - 1);
                    nota.setDespesa(d.getCod_objeto());

                    if(this.emp != null){
                        nota.setEmpreendimento(this.emp.getCod_objeto());
                    }
                    else map = false;
                }
            }
        }
        else{
            nota.setFornecedor(
                        fornecedor != null ? fornecedor.getCod_objeto() : null);

            if(cbDespesa.getSelectedIndex() > 0){
                Despesa d = 
                        (Despesa)lstDesp.get(cbDespesa.getSelectedIndex() - 1);
                nota.setDespesa(d.getCod_objeto());
                nota.setDespesa(d != null ? d.getCod_objeto() : null);
            }
            else{
                nota.setDespesa("");
            }

            nota.setEmpreendimento(emp != null ? emp.getCod_objeto() : "");
        }
        return map;
    }

    // Seta os valores corretos no comboBox
    private void selectedCombo(String idDespesa, String idEmp){
        // Recupera a despesa
        Despesa desp = new Despesa();
        desp = desp.refresh(idDespesa);
        cbDespesa.setSelectedItem(desp.getDescricao());
    }

    // Realiza a apresentacao das unidades recuperadas no formulario
    private void mostraNota(NotaDespesa obj){
        // Formato padrao das dadas do sistema
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        DecimalFormat format = new DecimalFormat("0.00");

        nota = obj;

        // Apresenta os campos
        textNumNota.setText(obj.getNumNota().toString());
        textSerie.setText(obj.getSerie());
        textValorTotal.setText(
                           format.format(obj.getValorNota()).replace(',', '.'));

        // Recuperando o fornecedor
        fornecedor = new Pessoa();
        fornecedor = fornecedor.refresh(obj.getFornecedor());
        textFornecedor.setText(fornecedor.getNome());

        // Apresenta as datas
        textDtEmissao.setText(nota.getDtEmisao() != null ?
                                        sdf.format(nota.getDtEmisao()) : null);
        textDtEntrada.setText(nota.getDtEntrada() != null ?
                                        sdf.format(nota.getDtEntrada()) : null);

        emp = new Empreendimento();
        emp = emp.refresh(obj.getEmpreendimento());
        textEmpreendimento.setText(
           new Pessoa().recPessoaEmpreendimento(emp.getCod_objeto()).getNome());
        // Desabilita os campos para edicao
        selectedCombo(nota.getDespesa(), nota.getEmpreendimento());
        enableFields(false);
    }

    // Inicializa o estados de todos os botoes
    private void initializeMyComponents(){
        try{
            StateMachineButton.changeState(getLstButton(1),
                                                  StateMachineButton.INICIAL);
            StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
            populateComboDespesa();
            clearFields();
        }
        catch(IOException ex){}
    }

    // Volta ao estado da navegacao
    private void mudarEstadoNavegacao() throws IOException{

        if(lstObj != null){
            // Verifica se existe a posicao na lista
            boolean exists = this.posicao < this.lstObj.size() ? true : false;

            // Decrementa uma posicao caso a ultima tenha sido removida
            if(!exists) this.posicao--;

            // Verifica se a lista esta vazia
            if(lstObj.isEmpty()){
                clearFields();
                StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
            }
            // Verifica se o tamanho da lista e 1
            else{
                mostraNota((NotaDespesa)lstObj.get(this.posicao));

                if(lstObj.size() <= 1){
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                }
                else{
                    // Verifica qual a posicao que se encontra
                    if(this.posicao == 0){
                        StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.PRIMEIRO);
                    }
                    else if(this.posicao == (lstObj.size() - 1)){
                        StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.ULTIMO);
                    }
                    else{
                        StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MAIOR);
                    }
                }
            }
        }
    }
    //</editor-fold>
}